#!/bin/bash

# 更新包索引并安装必要的工具
sudo apt-get update
sudo apt-get install -y apt-transport-https ca-certificates curl gnupg

# 添加 Kubernetes GPG 密钥
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.33/deb/Release.key | sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg

# 添加 Kubernetes APT 仓库
echo "deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v1.33/deb/ /" | sudo tee /etc/apt/sources.list.d/kubernetes.list

# 安装 Kubernetes 组件
sudo apt-get update
sudo apt-get install -y kubelet kubeadm kubectl
sudo apt-mark hold kubelet kubeadm kubectl

# 重启 Docker 以应用配置
sudo systemctl restart docker

# 启用 Docker 服务
sudo systemctl enable docker

# 启用 kubelet 服务
sudo systemctl enable --now kubelet

# 禁用 Swap
sudo swapoff -a
(crontab -l 2>/dev/null; echo "@reboot /sbin/swapoff -a") | crontab - || true

# 启用 IPv4 数据包转发
cat <<EOF | sudo tee /etc/sysctl.d/k8s.conf
net.ipv4.ip_forward = 1
EOF

# 应用 sysctl 参数而不重启
sudo sysctl --system

# 初始化 Kubernetes Master 节点
if [ "$1" == "master" ]; then
  sudo kubeadm init --pod-network-cidr=10.244.0.0/16
  mkdir -p $HOME/.kube
  sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
  sudo chown $(id -u):$(id -g) $HOME/.kube/config
  kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
elif [ "$1" == "worker" ]; then
  # 检查参数
  if [ "$#" -ne 3 ]; then
    echo "Usage: $0 <master-ip> <token> <discovery-token-ca-cert-hash>"
    exit 1
  fi
  MASTER_IP=$1
  TOKEN=$2
  DISCOVERY_TOKEN_CA_CERT_HASH=$3
  sudo kubeadm join $MASTER_IP:6443 --token $TOKEN --discovery-token-ca-cert-hash sha256:$DISCOVERY_TOKEN_CA_CERT_HASH
else
  echo "Usage: $0 {master|worker}"
  exit 1
fi